#include "data_manager.h"
#include "control.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdatomic.h>
#include <linux/limits.h>
#ifdef _WIN32
#include <pthread.h>
#else
#include <pthread.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#include <direct.h>
#include <io.h>
#else
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#endif

#ifdef _WIN32
#define MKDIR(path) mkdir(path)
#else
#define DIR_PERMISSIONS 0755
#define MKDIR(path) mkdir(path, DIR_PERMISSIONS)
#endif


#ifdef _WIN32
static const char *DATA_FILE_PATH = "C:\\ProgramData\\car_dashboard\\driving_data.txt";
#else
static const char *DATA_FILE_PATH = "/home/ubuntu/.car_dashboard_data/driving_data.txt";
#endif

atomic_bool data_generation_in_progress = false;

// 确保数据目录存在
static bool ensure_data_directory(void)
{
    char dir_path[256];
    strncpy(dir_path, DATA_FILE_PATH, sizeof(dir_path) - 1);
    dir_path[sizeof(dir_path) - 1] = '\0';
    char *last_slash = strrchr(dir_path, '/');
    #ifdef _WIN32
    if (!last_slash)
        last_slash = strrchr(dir_path, '\\');
    #endif
    if (last_slash)
    {
        *last_slash = '\0';
        if (MKDIR(dir_path) == -1)
        {
    #ifdef _WIN32
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
    #else
            if (errno != EEXIST)
            {
    #endif
                /* 日志已移除 */
                return false;
            }
        }
    }
    return true;
}

// 加载保存的数据
static bool load_saved_data(void)
{
    SystemState *state; // 声明state变量
    // 已在函数开头声明state变量，此处无需重复定义
    state = get_system_state();
    if (!state) {
        log_message(LOG_ERROR, "获取系统状态失败");
        return false;
    }
    FILE *file = fopen(DATA_FILE_PATH, "r");
    if (!file)
    {
        return true; // 文件不存在是正常情况，使用默认值
    }

    if (fscanf(file, "%u %u %u %f",
               &state->current_data.total_distance,
               &state->current_data.driving_distance,
               &state->current_data.driving_time,
               &state->current_data.fuel_consumption) != 4)
    {
        /* 日志已移除 */
        fclose(file);
        return false;
    }

    fclose(file);
    // 加载时限制总里程不超过15000
    if (state->current_data.total_distance > 15000) {
        state->current_data.total_distance = 15000;
    }
    state->current_data.is_initialized = true;
    return true;
}

// 初始化数据管理器
void data_manager_init(void)
{
    init_mutex(); // 确保互斥锁在数据操作前初始化
    SystemState *state = get_system_state();
    if (!state) {
        log_message(LOG_ERROR, "获取系统状态失败");
        return;
    }
    
    // 只需确保数据结构的默认值
    memset(&state->current_data, 0, sizeof(DrivingData));
    state->current_data.last_update = time(NULL);
}

// 重置当前行驶数据
bool reset_driving_data(void)
{
    SystemState *state = get_system_state();
    if (!state) {
        log_message(LOG_ERROR, "获取系统状态失败");
        return false;
    }
    if (!LOCK_DATA()) {
        log_message(LOG_ERROR, "Failed to acquire lock in reset_driving_data");
        return false;
    }
    // 保存总里程，重置当前数据
    // 限制总里程不超过15000
    // 长按确认键清除总里程记录
    state->current_data.total_distance = 0;
    state->current_data.driving_distance = 0;
    state->current_data.driving_time = 0;
    state->current_data.fuel_consumption = 0.0f;
    state->data_modified = true;
    
    save_driving_data(false);

    bool result = save_driving_data(false);
    if (result)
    {
        
    }
    UNLOCK_DATA();
    return result;
}

// 清理数据管理器资源
void data_manager_cleanup(void)
{
    SystemState *state = get_system_state();
    if (!state) {
        log_message(LOG_ERROR, "获取系统状态失败");
        return;
    }
#ifdef _WIN32
    DeleteCriticalSection(&state->data_mutex);
#else
    pthread_mutex_destroy(&state->data_mutex);
#endif
}

// 保存行驶数据到文件
bool save_driving_data(bool lock)
{
    char path[PATH_MAX];
    if (!get_data_path(path, sizeof(path))) {
        log_message(LOG_ERROR, "获取数据路径失败");
        return false;
    }

    FILE *fp = fopen(path, "wb");
    if (!fp) {
        log_message(LOG_ERROR, "无法打开文件: %s", path);
        return false;
    }

    bool success = false;
    if (lock) {
        if (!LOCK_DATA()) {
            log_message(LOG_ERROR, "Failed to acquire lock in save_driving_data");
            fclose(fp);
            return false;
        }
    }
    if (fwrite(&system_state.current_data, sizeof(DrivingData), 1, fp) != 1) {
        log_message(LOG_ERROR, "写入数据失败");
    } else {
        success = true;
    }
    if (lock) UNLOCK_DATA();

    fclose(fp);
    return success;
}

// 获取当前行驶数据
DrivingData get_current_driving_data(void)
{
    DrivingData result;
    SystemState *state = get_system_state();
    if (state) {
        if (!LOCK_DATA()) {
            log_message(LOG_ERROR, "Failed to acquire lock in update_driving_data");
            return (DrivingData){0}; // 返回默认初始化的结构体
        }
    }
    if (state) {
        result = state->current_data;
    }
    if (state) {
        UNLOCK_DATA();
    }
    return result;
}

// 数据验证（只检查不修改）
bool validate_driving_data(const DrivingData *data) {
    if (!data) return false;
    
    return (data->driving_distance >= MIN_DISTANCE) &&
           (data->driving_distance <= MAX_DISTANCE) &&
           (data->driving_time >= MIN_TIME) &&
           (data->driving_time <= MAX_TIME) &&
           (data->fuel_consumption >= MIN_FUEL) &&
           (data->fuel_consumption <= MAX_FUEL) &&
           (data->total_distance >= data->driving_distance);
}

// 数据修正（自动调整非法值）
void sanitize_driving_data(DrivingData *data) {
    if (!data) return;
    
    data->driving_distance = CLAMP(data->driving_distance, MIN_DISTANCE, MAX_DISTANCE);
    data->driving_time = CLAMP(data->driving_time, MIN_TIME, MAX_TIME);
    data->fuel_consumption = CLAMP(data->fuel_consumption, MIN_FUEL, MAX_FUEL);
    
    // 特殊规则：总里程必须 ≥ 当前行驶里程且不超过15000
    if (data->total_distance < data->driving_distance) {
        data->total_distance = data->driving_distance;
    }
    if (data->total_distance > 15000) {
        data->total_distance = 15000;
    }
    
    // 油耗与里程的关联规则
    if (data->driving_distance >= 500) {
        float min_fuel = 5.0f + (data->driving_distance / 1000.0f);
        data->fuel_consumption = MAX(data->fuel_consumption, min_fuel);
    }
}

// 更新行驶数据
void update_driving_data(uint32_t distance_delta, uint32_t time_delta, float fuel_delta)
{
    SystemState *state = get_system_state();
    if (!state || !state->current_data.is_initialized)
    {
        log_message(LOG_ERROR, "数据管理器尚未初始化或系统状态为空");
        return;
    }
    state = get_system_state();
    if (!state) {
        log_message(LOG_ERROR, "System state is NULL in update_driving_data");
        return;
    }

#ifdef _WIN32
    EnterCriticalSection(&state->data_mutex);
#else
    pthread_mutex_lock(&state->data_mutex);
#endif

    state->current_data.driving_distance += distance_delta;
    state->current_data.driving_time += time_delta;

    // 计算油耗 (仅当有行驶距离时)
    if (state->current_data.driving_distance > 0)
    {
        state->current_data.fuel_consumption += (fuel_delta / (float)state->current_data.driving_distance) * 100.0f;
    }

#ifdef _WIN32
    LeaveCriticalSection(&state->data_mutex);
#else
    pthread_mutex_unlock(&state->data_mutex);
#endif
}